package net.sahv.bdyz.controller.web;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sahv.bdyz.model.Member;
import net.sahv.bdyz.model.Orders;
import net.sahv.bdyz.service.MemberService;
import net.sahv.bdyz.service.OrdersService;
import net.sahv.bdyz.util.AlipayNotify;
@Controller
@RequestMapping(value="api")
public class Pay {

	 @Autowired
	 private OrdersService ordersService;
	 @Autowired
	 private MemberService memberService;
	/**支付宝post回调接口
     * 用于支付宝主动通知商户对订单一些状态变化的通知
     *@author 
     *@param request
     *@param response
     *@return
     *@throws UnsupportedEncodingException
     *@time 
     */
	@ResponseBody
	@RequestMapping(value = "/ZhifuPay")
    public String aliPostCallBack(HttpServletRequest request ,HttpServletResponse response) throws UnsupportedEncodingException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数
        //商户订单号
//        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        String out_trade_no = new String(request.getParameter("out_trade_no"));
        //用户id
       // String userId=new String(request.getParameter("subject").getBytes("ISO-8859-1"),"UTF-8");
        //描述
       // String remarks=new String(request.getParameter("body").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //金额
        String money = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"),"UTF-8");
        //交易状态
//        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        String trade_status = new String(request.getParameter("trade_status"));
        String extra_common_param;
        if(request.getParameter("extra_common_param")!=null){
        	 extra_common_param = new String(request.getParameter("extra_common_param")); //关键
        }else{
        	 extra_common_param="";
        }
    
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
		if (AlipayNotify.verify(params)) {// 验证成功
			// ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
				if (!extra_common_param.equals("")) {
					Member member = memberService.selectByPrimaryKey(Integer.valueOf(extra_common_param));
					member.setmVip(1);
					memberService.updateByPrimaryKey(member);
					return "success";
				}else{
					 Orders order = ordersService.selectByNo(out_trade_no);
					 order.setoState(1);
					 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					 order.setoFabricNo(format.format(new Date()));
					 ordersService.updateByPrimaryKey(order);
					 ordersService.mianliao(order);
					 return "success";
				}
			}else{
				return "payFalse";
			}
		}else{// 验证失败
			return "payFalse";

		}
    }
	
	@RequestMapping(value = "/ZhifuPaytubu")
    public String ZhifuPaytubu(Model model,HttpServletRequest request ,HttpServletResponse response) throws UnsupportedEncodingException {
	        if(request.getParameter("extra_common_param")!=null){
	        	return "redirect:/web/main/index";
	        }else{
	        	return "redirect:/member/member/myOrder-3/index";
	        }
		
	

	}
}
